<?php


/*
 * Edit by xinli
 * Click nbfs://nbhost/SystemFileSystem/Templates/Scripting/PHPClass.php to edit this template
 */

namespace api\mall\controller;

use cmf\controller\RestBaseController;
use think\facade\Db;
use think\facade\Log;
use api\mall\model\IMRelationModel;
/**
 * Description of IMRelationController
 *
 * @author PC
 */
class IMRelationController extends RestBaseController{
    protected function initialize() {
        parent::initialize();
        if (empty($this->user)) {
            $this->error('login');
        }
    }

    public function add() {
        $data = $this->request->post();
        if (empty($data['smallid']) || empty($data['bigid'])) {
            $this->error('parameter error');
        }

        $smallid = (int)$data['smallid'];
        $bigid = (int)$data['bigid'];

        $relationModel = new IMRelationModel();
        $relation = $relationModel->where('smallid', $smallid)->where('bigid', $bigid)->find();
        $relationid = 0;
        if (empty($relation)) {
            $relation = [
                'smallId'   => $smallid,
                'bigId'     => $bigid,
                'status'    => 0,
                'created'   => time(),
                'updated'   => time()
            ];
            $relationid = $relationModel->insertGetId($relation);
        }
        else {
            $relationid = $relation['id'];
            $relation = [];
            $relation['updated'] = time();
            $relation['status'] = 0;
            $relationModel->where('id', $relationid)->update($relation);
        }
        $this->success('ok');
    }

    public function delete() {
        $data = $this->request->post();
        if (empty($data['smallid']) || empty($data['bigid'])) {
            $this->error('parameter error');
        }

        $smallid = (int)$data['smallid'];
        $bigid = (int)$data['bigid'];

        $relationModel = new IMRelationModel();
        $relation = $relationModel->where('smallid', $smallid)->where('bigid', $bigid)->find();
        if (empty($relation)) {
            $this->error('record not found');
        }

        $relationid = $relation['id'];
        $relation = [];
        $relation['updated'] = time();
        $relation['status'] = 1;
        $relationModel->where('id', $relationid)->update($relation);
        $this->success('ok');
    }

    public function select() {
        // $data = $this->request->post();
        // if (empty($data['userid'])) {
        //     $this->error('parameter error');
        // }

        $userid = $this->getUserId();//(int)$data['userid'];

        $relationModel = new IMRelationModel();
        $data = $relationModel->whereOr('smallid|bigid', $userid)->where('status', 0)->select();
        $items = $data->toArray();
        $this->success('ok', $items);
    }

    public function test() {
        $this->success('ok', $this->getUserId());
    }
}
